package com.chezai.client.server;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.utils.LocationUtils;
import com.jx.driving.domain.GnssPackage;
import com.jx.driving.request.Terminal0x0200Request;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * 上报位置信息
 * Created by likunyang on 2017/12/11.
 */

public class UploadGnssService extends Service {

    private static final String TAG = UploadGnssService.class.getSimpleName();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Logger.t(TAG).i("Upload Gnss service create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return START_REDELIVER_INTENT;
    }

    @Subscribe
    public void onEventLocation(Location location) {
        if (!Const.IS_STOP_UPLOAD_GNSS) {
            uploadGnss(location);
        }
    }

    private void uploadGnss(Location location) {
        if (!TerminalSocketClientManager.getInstance().isConnect() || !TerminalSocketClientManager.getInstance().isAuthenticated())
            return;
        GnssPackage gnssPackage = LocationUtils.getGnssPackage(location);
        if (gnssPackage.getLat() == 0 || gnssPackage.getLng() == 0) {
            return;
        }
        Terminal0x0200Request x0200 = new Terminal0x0200Request();
        x0200.setGnss(gnssPackage);
        x0200.setAttachementList(TerminalApplication.getTerminalContext().getLocationAttachement());
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(x0200);
    }

    @Override
    public void onDestroy() {
        Logger.t(TAG).i("Upload Gnss service stop");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        Intent i = new Intent(Const.RESTART_UPLOAD_GNSS_SERVICE);
        sendBroadcast(i);
    }
}
